using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CodeStory.WebControls
{
	/// <summary>
	/// ConfirmButton is a button control,which will show a confirm dialog
	/// to allow users to make sure what to do.
	/// </summary>
	[DefaultProperty("Text")]
	[ToolboxData("<{0}:ConfirmButton runat=server></{0}:ConfirmButton>")]
	public class ConfirmButton : Button
	{
		static int k = 0;
		public ConfirmButton() {
			k++;
		}
		string scriptHashcode;
		public string ConfirmText {
			get {
				object obj = ViewState["ConfirmText"];
				return obj == null ? string.Empty : (string)obj;
			}
			set { 
				ViewState["ConfirmText"] = value;
				scriptHashcode = Math.Abs(value.GetHashCode()).ToString();
			}
		}

		protected override void AddAttributesToRender(HtmlTextWriter writer) {
			if (ConfirmText != null && ConfirmText.Length > 0)
				writer.AddAttribute("OnClick", GetCallScript());
			base.AddAttributesToRender(writer);
		}
		protected override void OnPreRender(EventArgs e) {
			if (ConfirmText != null && ConfirmText.Length > 0)
				Page.ClientScript.RegisterStartupScript(
					this.GetType(),
					scriptHashcode,
					GetConfirmScript()
				);
			base.OnPreRender(e);
		}
		protected override void Render(HtmlTextWriter writer) {
			Page.ClientScript.RegisterForEventValidation(this.UniqueID);
			base.Render(writer);
		}

		private string GetCallScript() {
			return string.Format("return Confirm_{0}();",scriptHashcode);
		}

		private string GetConfirmScript() {
			//throw new Exception("The method or operation is not implemented.");
			string script = 
@"
<script type=""text/javascript"">
<!--
function Confirm_" + scriptHashcode + @"(){
	return window.confirm(""" + ConfirmText + @""");
}
-->
</script>";
			return script;
		}

		protected override object SaveViewState() {
			object obj = ((IStateManager)base.ViewState).SaveViewState();
			return base.SaveViewState();
		}
	}
}
